import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Tabs } from 'antd';
import { useDrop } from 'react-dnd';
import {
  PieChartOutlined,
  PlayCircleOutlined,
  HighlightOutlined,
  DoubleRightOutlined,
  DoubleLeftOutlined,
  AppstoreOutlined,
} from '@ant-design/icons';
import { connect } from 'dva';
import HeaderComponent from './components/Header';
import { componentsType } from '@/core/DynamicEngine';
import FormConfig from './components/FormConfig';
import { ActionCreators, StateWithHistory } from 'redux-undo';
import { usePostMsg, useDragMark } from './hooks';
import { getFromConfig } from './utils';
import VTargetBox from './components/TargetBox';
import styles from './index.less';

const { TabPane } = Tabs;
const domain = 'http://127.0.0.1:3000';
const CpIcon = {
  base: <HighlightOutlined />,
  media: <PlayCircleOutlined />,
  visible: <PieChartOutlined />,
  shop: <AppstoreOutlined />,
};

const Container = (props: { location?: any; dispatch?: any }) => {
  const { dispatch } = props;
  const [collapsed, setCollapsed] = useState(false);
  const gConfig = useRef<any>({});
  const [dataConfig, setDataConfig] = useState([]);
  const [fromConfig, setFromConfig] = useState([]);

  const { sentMeg, iframeRef } = usePostMsg({
    domain,
    postMsg: function(data: any) {
      if (data.code === 'config') {
        gConfig.current.dataConfig = data.data;
        setDataConfig(data.data);
      } else if (data.code === 'form') {
        setFromConfig(getFromConfig(gConfig.current.dataConfig, data.data));
      }
    },
  });
  const showDragMark = useDragMark(sentMeg);

  const changeCollapse = useMemo(() => {
    return (c: boolean) => {
      setCollapsed(c);
    };
  }, []);

  const generateHeader = useMemo(() => {
    return (type: componentsType, text: string) => {
      return <div>{CpIcon[type]}</div>;
    };
  }, [CpIcon]);

  const clearData = useCallback(() => {
    dispatch({ type: 'editorModal/clearAll' });
  }, [dispatch]);

  const redohandler = useMemo(() => {
    return () => {
      dispatch(ActionCreators.redo());
    };
  }, [dispatch]);

  const undohandler = useMemo(() => {
    return () => {
      dispatch(ActionCreators.undo());
    };
  }, [dispatch]);

  const importTpl = (data: any) => {
    dispatch({
      type: 'editorModal/importTplData',
      payload: data,
    });
  };

  const [{}, drop] = useDrop({
    accept: 'component',
    drop: () => ({ name: 'Dustbin' }),
    collect: monitor => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
  });

  const handledrop = (item: any) => {
    sentMeg({
      code: 'drop',
      data: item,
    });
  };

  const tabRender = useMemo(() => {
    if (collapsed) {
      return (
        <>
          {dataConfig.map((val: any) => {
            return <TabPane tab={generateHeader(val.name, '')} key={val.name}></TabPane>;
          })}
        </>
      );
    } else {
      return (
        <>
          {dataConfig.map((val: any) => {
            return (
              <TabPane tab={generateHeader(val.name, '')} key={val.name}>
                <div className={styles.ctitle}>{val.title}</div>
                {val.list.map((value: any, i: number) => (
                  <VTargetBox item={value} key={i} drop={handledrop} />
                ))}
              </TabPane>
            );
          })}
        </>
      );
    }
  }, [collapsed, dataConfig]);

  return (
    <div className={styles.editorWrap}>
      <HeaderComponent
        redohandler={redohandler}
        undohandler={undohandler}
        pointData={{}}
        clearData={{}}
        location={{}}
        importTpl={importTpl}
      />
      <div className={styles.container}>
        <div
          className={styles.list}
          style={{
            transition: 'all ease-in-out 0.5s',
            position: 'fixed',
            width: collapsed ? '50px' : '350px',
            zIndex: 200,
            boxShadow: 'none',
          }}
        >
          <div className={styles.componentList}>
            <Tabs
              className="editorTabclass"
              onTabClick={() => changeCollapse(false)}
              defaultActiveKey="1"
              tabPosition={'left'}
            >
              {tabRender}
            </Tabs>
          </div>
          <div
            className={styles.collapsed}
            style={{ position: 'absolute', bottom: '80px', left: '20px' }}
            onClick={() => changeCollapse(!collapsed)}
          >
            {collapsed ? <DoubleRightOutlined /> : <DoubleLeftOutlined />}
          </div>
        </div>
        <div
          style={{
            width: collapsed ? '50px' : '350px',
            transition: 'all ease-in-out 0.5s',
          }}
        ></div>

        <div className={styles.tickMark}>
          <iframe
            ref={iframeRef}
            className={styles.preview_iframe}
            src={domain}
            frameBorder="0"
            allowFullScreen
            width="100%"
          />
        </div>
        <FormConfig config={fromConfig} />
        {showDragMark && <div className={styles.dragMark} ref={drop}></div>}
      </div>
    </div>
  );
};

export default connect((state: StateWithHistory<any>) => {
  return { pstate: state.present.editorModal, cstate: state.present.editorPcModal };
})(Container);
